package com.sunnada.edu.system.pub.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.DESJAVA;
import com.sunnada.edu.system.pub.util.Utils;




@Service
@Transactional
public class PubServiceImpl implements PubService {
    
	
	/**
	 * 1.验证账号的信息和短信状态
	 * */
	@Override
	public String getForgetMsgState(HashMap<String, String> params) {
		String userId=params.get("userId");
		String msg="";
		if(Utils.isNull(userId)){
			msg = "1,没有填写用户名！";			
		}else{
			if(isUserExists(params)){
			    msg=isCanSendMsg(params);  	    //判断一下用户是否可以获取短信验证码 , 5：短信验证
			}else{
			    msg = "1,当前用户名不存在！";
			}
		}		
		return msg;
	}
	
	/**
	 * 2.获取短信短信状态
	 * */
	@Override
	public String pubgetSMsg(HashMap<String, String> params) {
		String msg="";//0:非联通号码 1：入库成功，返回验证码对应id 2:入库失败 
		String tel= getUserTel(params);
		params.put("tel",tel);
		msg=userMsgState(params);                    //判断手机号码获取短信的状态
		if(Utils.isNull(msg)){
		  String recId= getMsgCode(params);          //获取短信
		  String trimTel=tel.substring(0,3)+"****"+tel.substring(7,11);
		  msg="2,"+trimTel+","+recId;
		}else{
			msg= "3,请在一分钟之后重新获取短信！";
		}	
		return  msg;
	}
	

	/**
	 * 3.修改登录密码
	 * */
	@Override
	public String clientForgetsLogin(HttpServletRequest request) {
		String msg="";
		String userId = request.getParameter("userId");
		String pwd = request.getParameter("pwd");     
		String pwd1 = request.getParameter("pwd1");     
		String code = request.getParameter("code");
		String key=(String) request.getSession().getAttribute(Constants.DESSTRING);
	    userId= DESJAVA.strDec(userId, key,null,null);
	    pwd= DESJAVA.strDec(pwd, key,null,null);
	    pwd1= DESJAVA.strDec(pwd1, key,null,null);
	    if(Utils.isNotNull(pwd)&&Utils.isNotNull(pwd1)){
	    	if(!pwd.equals(pwd1)){
				msg = "新密码和确认新密码不一致！";
			}else{
			/*	if(!Utils.testPWD(pwd)){
					msg="密码长度为6到20之间:必须含有小写字母、大写字母、数字、特殊符号中的任意三种";
				}else{*/
					if(Utils.isNotNull(code)){
						HashMap<String, String> map=new HashMap<String, String>();
                        map.put("userId", userId);
						String tel= getUserTel(map);
						map.put("tel",tel );
						map.put("code",code);
						if(isSmsCodeOk(map)){
							Map user=getUserInfo(map); 
							if(user!=null){
								String sysuserId=(String) user.get("USER_ID");
								String password=MD5.md5(sysuserId+pwd);
								map.put("password", password);
								int num= updateUserPwd(map);
								if(num==0){
									msg="修改失败";
								}
							}else{
								msg = "用户不存在！";
							}			
						}else{
							msg = "短信码不正确，请重新输入！";
						}
					}else{
						msg = "短信验证码不能为空！";
					}	
				}
		/*	}*/
	    }else{
	    	msg = "密码不能为空！";
	    }
	    return msg;
	}
	
	
	
	
	
	
	
  
	


	//获取的短信
	private String getMsgCode(HashMap<String, String> params) {
    	 String recId=PubMethods.getBatchId();    
    	 String smcode=RandomGUID.getrannumber();//6位验证码
    	 String smessage="您正在修改智慧家校系统登录密码,请输入手机验证码【"+smcode+"】,有效期：6分钟。【智慧家校】";
    	 params.put("batchId", recId);
    	 params.put("sendType", "5");
    	 params.put("content",smessage);
    	 params.put("state","0");
         PubMethods.insertMessage(params);
         insertMessage(params);
         return recId;
	 }

	public int insertMessage(HashMap<String, String> params){	
		PubDao dao = AppContext.getInstance().getPubDao();
		String batchId=params.get("batchId");
		String tel=params.get("tel");
		String loginAreaCode=params.get("loginAreaCode");
		String sendType=params.get("sendType");
		String content=params.get("content");
		String state="0";//状态(0:未处理 1：已处理)
		String sql="INSERT INTO T_TEMP_MESSAGE_HIS(BATCH_ID,TEL,AREA_CODE,SEND_TYPE,CONTENT,REC_TIME,REC_STATE,SEND_TIME) "
				+ "values('"+batchId+"','"+tel+"','"+loginAreaCode+"','"+sendType+"','"+content+"',sysdate,'"+state+"',sysdate)";
		int num=dao.insert(sql);	
		return num;
	}
	
	
	//1.判断用户是否存在
	private boolean isUserExists(HashMap<String, String> params) {
		String userId=params.get("userId");
		PubDao dao = AppContext.getInstance().getPubDao();
		String sql=" select 1 from s_sysuser where USER_LOGINCODE='"+userId+"' and rec_status='0'";
		List<?> list =  dao.selectList(sql);
		if(list!=null&&list.size()>0){
			return true;
		}
		return false;
	}

	//2.验证用户账号是否可以发送短信
	private String isCanSendMsg(HashMap<String, String> params) {
		String msg="";
		String tel = getUserTel(params);     //获取账号的手机号码
		if(Utils.isNotNull(tel)){
			params.put("tel",tel);
			msg=userMsgState(params);        //判断手机号码获取短信的状态
		}else{
			msg="1.当前账号没有绑定手机号码";
		}
		return msg;
	 }
	
	
	//3.获取账号的手机号码
	@SuppressWarnings("rawtypes")
	private String getUserTel(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId=params.get("userId");
	    String  sql="select  PHONE from s_sysuser where USER_LOGINCODE='"+userId+"' and rec_status='0'";
		List<?> phonel = dao.selectList(sql);   
		if(phonel!=null&&phonel.size()>0){
			 return (String)((Map)phonel.get(0)).get("PHONE");
		}
		return null;
	}
	//4.判断当前用户手机短信码的状态
	@SuppressWarnings("rawtypes")
	private String userMsgState(HashMap<String, String> params) {
		String msg="";
		PubDao dao = AppContext.getInstance().getPubDao();
		String tel=params.get("tel");
		String phoneMsgState=" select  to_char((sysdate-t.rec_time)*24*60*60 ) as  mis  from T_TEMP_MESSAGE_HIS t  where TEL='"+tel+"' and t.SEND_TYPE='5' and (sysdate-t.REC_TIME)*24*60<1 "; 
	 	List<?> phoneTimestate= dao.selectList(phoneMsgState);   
		String mis="0";
	    if(phoneTimestate!=null&&phoneTimestate.size()>0){		// 获取短信发送前先判断短信验证码的状态 ：短信验证码1分钟只能发送一次    并且两次短信的相差的时间
		     String ll=((Map)phoneTimestate.get(0)).get("MIS").toString();
			 mis=ll;
			 msg="3,"+mis;
		}
		return msg;
	}
	
	//5.获取登录账号信息
	@SuppressWarnings("rawtypes")
	private Map getUserInfo(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId=params.get("userId");
	    String  sql="select  * from s_sysuser where USER_LOGINCODE='"+userId+"' and rec_status='0'";
		List<?> user = dao.selectList(sql);   
		if(user!=null&&user.size()>0){
			 return ((Map)user.get(0));
		}
		return null;
	}
	
	
    
	//6.短信验证码验证
    private boolean isSmsCodeOk(HashMap<String, String> params) {
    	PubDao dao = AppContext.getInstance().getPubDao();
		String tel=params.get("tel");
		String code=params.get("code");
		String sql="select 1 from ( select * from  (select * from  T_TEMP_MESSAGE_HIS where  tel='"+tel+"' and  send_type='5' order  by rec_time desc  ) t1  where rownum=1 )t2 where  t2.content like '%手机验证码【"+code+"】%' and (sysdate-t2.rec_time)*24*60<6 ";
		List<?> list = dao.selectList(sql);
		if(list!=null&&list.size()>0){
			return true;
		}
		return false; 
	}

    //7.修改密码
	private int updateUserPwd(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId=params.get("userId");
		String password=params.get("password");
		String sql="update S_SYSUSER set  LOGIN_PWD='"+password+"' where USER_LOGINCODE='"+userId+"'";
		return dao.update(sql);	
	}

}
